<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2018/1/21
 * Time: 19:04
 */
namespace common\models;

use common\models\ar\Images;
use common\models\ar\RealName;
use common\models\ar\RealNameTmp;
use common\models\ar\User;
use common\models\ar\UserBrokers;

class RealNameDao
{
    public static function lists(
        $uid = -1,
        $status = -1
    ) {
        $db = \Yii::$app->db;

        $sql_lists = "SELECT a.*, a.`loginName`, a.`accountName` FROM  `real_name` a ";
        $sql_where = '';
        // $sql_join = 'LEFT JOIN `user` b ON a.`userID` = b.`userID` ';
        $sql_orderBy = ' ORDER BY a.`update_time` DESC ';

        $bind_arr = [];
        $tmpWhere = [];
        if ($uid != -1) {
            $tmpWhere[] = 'a.`loginName` ='.$uid;
            // $bind_arr[':uid'] = $uid;
        }
        //审核状态
        $tmpWhere[] = 'a.`update_status` != 0';
        if ($status != -1) {
            // $bind_arr[':update_status'] = $status;
            $tmpWhere[] = 'a.`update_status` ='.$status;   
        }
        if (!empty($tmpWhere)) {
            $sql_where = 'WHERE ' . implode(' AND ', $tmpWhere);
        }
       // var_dump($sql_lists);
       // var_dump($sql_join);
       // var_dump($sql_where);
       // var_dump($sql_orderBy);
       // exit();
        return $db->createCommand($sql_lists . $sql_where . $sql_orderBy)->queryAll();
        //exit();
    }

    /**
     * 客户提交实名信息
     *
     * @param $uid
     * @param $fields
     * @param $updateFields
     *
     * @return bool
     */
    public static function submit($uid, $fields, $updateFields,$Name,$level,$loginNames)
    {
        $time = time();
        try {
            if ($level==2) {
            $up_real_flag=UserBrokers::findOne(["id"=>$uid]);
            $up_real_flag->login_flag=3;
            $up_real_flag->save(false);
            }
            $tmp = RealName::findOne($uid);
            if (!$tmp) {
                $tmp = new RealName();
                $tmp->attributes = [
                    'userID' => $uid,
                    'status' => 0,
                    'progress' => 1,
                    'update_time' => $time,
                    'update_status' => 1,
                    'update_error_msg' => '',
                    'accountName'=>$Name,
                    'level'=>$level,
                    'loginName'=>$loginNames
                ];
                // var_dump($tmp);
                // exit();
                $tmp->save(false);
            } else {
                $tmp->update_time = $time;
                $tmp->update_status = 1;
                $tmp->update_error_msg = '';
                $tmp->save(false);
            }
            $sqlArr = [];
            foreach ($updateFields as $k => $v) {
                //如果是图片类型，将图片保存到images表中
                if ($fields[$k]['type'] == 5) {
                    $image = new Images();
                    $image->attributes = [
                        'userID' => $uid,
                        'user_type' => 1,
                        'create_time' => $time,
                        'value' => $v
                    ];
                    $image->save();
                    $v = $image->id;
                    //删除该用户之前数据库中保存的实名图片
                    $tmp = RealNameTmp::find()->where(['userID' => $uid, 'field_id' => $k])->one();
                    if ($tmp) {
                        $sql = "DELETE FROM `images` WHERE `id` = " . $tmp['field_value'] . " AND `userID` = " . $uid;
                        \Yii::$app->db->createCommand($sql)->execute();
                    }
                }

                $sqlArr[] = "($uid, $k,'" . $v . "')";
            }
            $sql = "INSERT INTO `real_name_tmp` 
                      (`userID`, `field_id`, `field_value`) 
                    VALUES 
                      " . implode(",", $sqlArr) . "
                    ON DUPLICATE KEY UPDATE `field_value` = VALUES(`field_value`)
            ";
            \Yii::$app->db->createCommand($sql)->execute();
            $bool = true;
        } catch (\Exception $e) {
            $bool = false;
        }

        return $bool;
    }

    /**
     * 后台审核
     *
     * @param $uid
     * @param $type
     * @param string $msg
     * @return bool
     */
    public static function operate($uid, $type, $msg = '')
    {
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if ($type == 0) {//拒绝
                $sql = "UPDATE `real_name` 
                        SET 
                          `update_status` = 3,
                          `update_error_msg` = '" . $msg . "' 
                        WHERE 
                            `userID` = $uid
                ";
                $db->createCommand($sql)->execute();
            } else if($type == 1){//同意
                //转移到user_info_detail表
                $sql = "SELECT * FROM `real_name_tmp` WHERE `userID` = $uid";
                $fields = $db->createCommand($sql)->queryAll();
                foreach ($fields as $v) {
                    $sql = "INSERT INTO `user_info_detail` 
                              (`userID`,`field_id`,`field_value`) 
                            VALUES 
                              (:uid,:id,:val) 
                            ON DUPLICATE KEY UPDATE `field_value` = :val";
                    $db->createCommand($sql, [
                        ':uid' => $uid,
                        ':id' => $v['field_id'],
                        ':val' => $v['field_value']
                    ])->execute();
                }
                //删除tmp表中的提交记录
                $sql = "DELETE FROM `real_name_tmp` WHERE `userID` = $uid";
                $db->createCommand($sql)->execute();

                //更新状态
                $sql = "UPDATE `real_name` 
                        SET 
                          `status` = 1,
                          `progress` = 1,
                          `update_time` = unix_timestamp(now()),
                          `update_status` = 2,
                          `update_error_msg` = '' 
                        WHERE 
                            `userID` = $uid
                ";
            $db->createCommand($sql)->execute();
            $Real=RealName::findOne(["userID"=>$uid]);
            if ($Real['level']==1){
                $users=User::findOne($uid);
                $users->login_flag=1;
            }else{
                $users=UserBrokers::findOne($uid);
                $users->login_flag=1;
            }
             $users->save(false);
            }
            else if ($type == 9){
                $sql = "UPDATE `real_name` 
                        SET 
                          `status` = 9,
                          `progress` = 1,
                          `update_time` = unix_timestamp(now()),
                          `update_status` = 9,
                          `update_error_msg` = '当前用户实名信息功能存在问题，请通知管理员！' 
                        WHERE 
                            `userID` = $uid";
                $db->createCommand($sql)->execute();
            }
            $transaction->commit();
            $return = true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $return = false;
        }
        return $return;
    }
}